package com.edu.demo.controller;

import com.edu.demo.entity.Student;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IStudentService;
import com.edu.demo.utils.SecurityUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 返回学生信息
     * @return
     */
    @GetMapping("/info")
    @PreAuthorize("@ps.hasPerm('stu:info:query')")
    public AjaxResult getMyInfo(){
        Student student = SecurityUtils.getStudent();student.setPassword(null);
        return AjaxResult.success(student);

    }

    /**
     * 更新学生自己信息
     * @param student
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("@ps.hasPerm('stu:info:update')")
    public AjaxResult updateInfo(@RequestBody Student student){
        student.setPassword(null);
        boolean b = studentService.updateById(student);
        return AjaxResult.success(b);
    }

    /**
     * 学生修改密码
     * @param para
     * @return
     */
    @PostMapping("/updatePassword")
    @PreAuthorize("@ps.hasPerm('stu:info:update')")
    public AjaxResult updatePassword(@RequestBody Map<String,Object> para){

        String oldPassword = (String) para.get("oldPassword"),newPassword = (String) para.get("newPassword");
        if(Strings.isEmpty(oldPassword) || Strings.isEmpty(newPassword))return AjaxResult.error("密码不能为空");
        Student student = SecurityUtils.getStudent();
        if(student.getPassword().equals(oldPassword))
        {
            Student student1 = new Student();
            student1.setId(student.getId());
            student1.setPassword(passwordEncoder.encode(newPassword));
            int i = studentService.updateStudent(student1);
            if(i==1) return AjaxResult.success();

        }

        return AjaxResult.error("服务异常，修改失败");

    }

}
